// pages/generalize/index.js
const app = getApp() // 引入app
import _request from '../../utils/request.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    invitecode: '',
    imgUrl: app.globalData.imgUrl, //全局img路径
    // imglist: [{
    //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/user_1.jpeg'
    //   },
    //   {
    //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/user_2.jpeg'
    //   },
    //   {
    //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/hairdresser_1.jpeg'
    //   },
    //   {
    //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/hairdresser_2.jpeg'
    //   },
    //   {
    //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/store_1.jpeg'
    //   },
    //   {
    //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/store_2.jpeg'
    //   },
    // ],
    imglist: [
    {
      img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/user_2.jpeg'
    },
    {
      img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/hairdresser_2.jpeg'
    },
    {
      img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/store_2.jpeg'
    },
  ],
    indicatorDots: false,
    vertical: false,
    autoplay: false,
    duration: 500,
    margin55: '',
    codeimg: '',
    showimg: '',
    bannerlist: '' // 合成后图片路径
  },

  // 轮播事件
  swiperChange(e) {
    let index = e.detail.current
    this.setData({
      showimg: this.data.bannerlist[index].img
    })
  },

  //点击图片进行预览，长按保存分享图片
  previewImg(e) {
    this.setData({
      showimg: e.currentTarget.dataset.item.img
    })
    let list = this.data.bannerlist.map(item=>{
      return item.img
    })
    wx.previewImage({
      current: e.currentTarget.dataset.item.img, // 当前显示图片的http链接
      urls: list // 需要预览的图片http链接列表
    })
  },

  // 分享海报
  onSharePoster() {
    let list = this.data.bannerlist.map(item=>{
      return item.img
    })
    wx.previewImage({
      current: this.data.showimg, // 当前显示图片的http链接
      urls: list // 需要预览的图片http链接列表
    })
  },

  // 合成海报
  // drawPoster(circleBg, qrCodeUrl) {
  //   circleBg.map((item, index) => {
  //     let id = 'shareCanvas' + index
  //     let posterCanvas = wx.createSelectorQuery().select('#' + id)
  //     return new Promise((resolve, reject) => {
  //       posterCanvas.fields({
  //         node: true,
  //         size: true
  //       }).exec(res => {
  //         const canvas = res[0].node
  //         const ctx = canvas.getContext('2d')
  //         const dpr = wx.getSystemInfoSync().pixelRatio
  //         canvas.width = res[0].width * dpr
  //         canvas.height = res[0].height * dpr
  //         // 绘制海报
  //         wx.getImageInfo({
  //           src: item.img,
  //           success: res => {
  //             let imageUrl = res.path // 图片临时地址
  //             let imageW = res.width
  //             let imageH = res.height
  //             let ratio = imageW / canvas.width // 获取比例
  //             let imageObj = canvas.createImage()
  //             imageObj.src = imageUrl
  //             imageObj.onload = (res) => {
  //               ctx.drawImage(imageObj, 0, 0, imageW / ratio, imageH / ratio);
  //               // 绘制二维码
  //               wx.getImageInfo({
  //                 src: qrCodeUrl,
  //                 success: res => {
  //                   let qrImageUrl = res.path
  //                   let qrImageW = 180 // 二维码大小
  //                   let qrRatio = ratio
  //                   let qrImageObj = canvas.createImage()
  //                   qrImageObj.src = qrImageUrl
  //                   qrImageObj.onload = (res) => {
  //                     // 图片,left,top,width,height
  //                     ctx.drawImage(qrImageObj, 50, canvas.height - (qrImageW + 100) / qrRatio, qrImageW / qrRatio, qrImageW / qrRatio)
  //                     // canvas转图片临时路径
  //                     wx.canvasToTempFilePath({
  //                       canvas: canvas,
  //                       fileType: 'png',
  //                       success: res => {
  //                         resolve(res)
  //                         this.setData({
  //                           bannerlist: [...this.data.bannerlist, {
  //                             'img': res.tempFilePath,
  //                             'id': index
  //                           }],
  //                         })
  //                         this.setData({
  //                           showimg: this.data.bannerlist[0].img
  //                         })
  //                       },
  //                       fail: err => {
  //                         reject(err)
  //                       }
  //                     })
  //                   }
  //                 },
  //                 fail: err => {
  //                   reject(err)
  //                 },
  //               })
  //             }
  //           },
  //           fail: err => {
  //             reject(err)
  //           },
  //         })
  //       })
  //     })
  //   })
  // },
  drawPoster1(circleBg, qrCodeUrl, index) {
    let id = 'shareCanvas' + index
    let posterCanvas = wx.createSelectorQuery().select('#' + id)
    return new Promise((resolve, reject) => {
      posterCanvas.fields({
        node: true,
        size: true
      }).exec(res => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        // 绘制海报
        wx.getImageInfo({
          src: circleBg,
          success: res => {
            let imageUrl = res.path // 图片临时地址
            let imageW = res.width
            let imageH = res.height
            let ratio = imageW / canvas.width // 获取比例
            let imageObj = canvas.createImage()
            imageObj.src = imageUrl
            imageObj.onload = (res) => {
              ctx.drawImage(imageObj, 0, 0, imageW / ratio, imageH / ratio);
              // 绘制二维码
              wx.getImageInfo({
                src: qrCodeUrl,
                success: res => {
                  let qrImageUrl = res.path
                  let qrImageW = 180 // 二维码大小
                  let qrRatio = ratio
                  let qrImageObj = canvas.createImage()
                  qrImageObj.src = qrImageUrl
                  qrImageObj.onload = (res) => {
                    // 图片,left,top,width,height
                    ctx.drawImage(qrImageObj, 50, canvas.height - (qrImageW + 100) / qrRatio, qrImageW / qrRatio, qrImageW / qrRatio)
                    // canvas转图片临时路径
                    wx.canvasToTempFilePath({
                      canvas: canvas,
                      fileType: 'png',
                      success: res => {
                        let data = {
                          'img': res.tempFilePath,
                          'id': index
                        }
                        resolve(data)
                      },
                      fail: err => {
                        reject(err)
                      }
                    })
                  }
                },
                fail: err => {
                  reject(err)
                },
              })
            }
          },
          fail: err => {
            reject(err)
          },
        })
      })
    })
  },

  // 数组排序
  sort(arr) {
    for (var j = 0; j < arr.length - 1; j++) {
      //两两比较，如果前一个比后一个大，则交换位置。
      for (var i = 0; i < arr.length - 1 - j; i++) {
        if (arr[i].id > arr[i + 1].id) {
          var temp = arr[i];
          arr[i] = arr[i + 1];
          arr[i + 1] = temp;
        }
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: res => {
        this.setData({
          data1: res
        })
      }
    });
    // 获取邀请码
    _request.get('/recomUser/findReCode', {
      userId: wx.getStorageSync('userid'),
    }).then((res) => {

      this.setData({
        invitecode: res.data.data.invitecode
      })
      // 获取邀请二维码
      _request.get('/basicSetting/getWXShareQrCode', {
        referralCode: this.data.invitecode,
        userId: wx.getStorageSync('userid')
      }).then((res) => {
        this.setData({
          codeimg: res.data.data
        })
      }).catch((error) => {
        console.log(error, 'error');
      })
    }).catch((error) => {
      console.log(error, 'error');
    })
    // 绘制背景海报到canvas
    const {
      imglist,
      codeimg,
      bannerlist
    } = this.data
    let list = []
    imglist.map((item, index) => {
      this.drawPoster1(item.img, item.img, index).then(res => {
        list.push(res)
        this.sort(list)
        this.setData({
          bannerlist: list,
          showimg: list[0].img
        })
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    let title = '意约小程序'
    return {
      title: title, // 默认是小程序的名称
      path: 'firstpages/home/index',
      success: function (res) {
      }
    }
  }
})